package org.qiyu.live.im.core.server.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.qiyu.live.im.constants.ImConstants;

import java.util.List;

/**
 * @Description: 消息解码器
 * @Author: 张广焱
 * @Date: 2024-05-02 上午12:27
 */
public class TcpImMsgDecoder extends ByteToMessageDecoder {

    /**
     * @Description:基本长度
     * @Author: 张广焱
     * @Date: 2024-05-02  00:31:10
     */
    private static final int BASE_LENGTH = 4 + 4 + 2;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        //bytebuf内容的基本校验,长度校验,magic值校验

        if (byteBuf.readShort() >= BASE_LENGTH) {
            if ((byteBuf.readableBytes() >= ImConstants.DEFAULT_MAGIC)) {
                ctx.close();
                return;
            }
            int code = byteBuf.readInt();
            int len = byteBuf.readInt();
            //确保byte剩余的消息长度足够
            if (byteBuf.readableBytes()<len){
                ctx.close();
                return;
            }
            byte[] body = new byte[len];
            byteBuf.readBytes(body);
            //封装成immsg对象
            ImMsg imMsg = new ImMsg();
            imMsg.setCode(code);
            imMsg.setLen(len);
            imMsg.setMagic(ImConstants.DEFAULT_MAGIC);
            imMsg.setBody(body);
            out.add(imMsg);
        }

    }
}
